import gtk,gobject
import re
import WindowTemplate

class RegexEditor(WindowTemplate.WindowTemplate):
    
    def __init__(self,controller):
        
        WindowTemplate.WindowTemplate.__init__(self,controller)
        self.regex = self.config.regex
        self.COLOR_WRONG = '#FF6060'
        self.COLOR_VALID = '#60FF60'
        self.create_window()
        
    def create_window(self):
        self.set_title('Regex Editor')
        self.set_size_request(600,120)
        self.global_vbox = gtk.VBox(False,5)
        self.add(self.global_vbox)
        
        self.create_ddl()
        
        self.lbl = gtk.Label()
        self.global_vbox.pack_start(self.lbl)
        self.tb = gtk.Entry()
        self.tb.connect('changed',self.validate)
        self.global_vbox.pack_start(self.tb)
        
        self.btn = gtk.Button(None, gtk.STOCK_APPLY)
        self.btn.connect('clicked',self.validate)
        self.global_vbox.pack_start(self.btn)
        self.validate()
        self.show_all()
        
    def create_ddl(self):
        '''create the location sorted combo box with an hidden column to store the location id'''
        
        # Listmodel
        self.listmodel = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING )
        self.fill_listmodel()
        
        # Drop Down List
        self.ddl = gtk.ComboBoxEntry(self.listmodel)
        self.ddl.connect("changed", self.regex_change_callback)
        self.global_vbox.pack_start(self.ddl)

    
    def fill_listmodel(self):
        for regex_name, regex in self.regex:
            self.listmodel.append((regex_name,regex))
    
    def get_regex(self):
        regex = self.ddl.get_active_text()
        if regex in self.regex.store:
            regex = self.regex[self.ddl.get_active_text()]
        return regex
    
    def regex_change_callback(self,tb):
        self.lbl.set_text(self.get_regex())
        self.validate()
    
    def validate(self,*args):
        try :
            if re.match(self.get_regex(),self.tb.get_text()):
                self.tb.modify_base(gtk.STATE_NORMAL,gtk.gdk.color_parse(self.COLOR_VALID))
            else:
                self.tb.modify_base(gtk.STATE_NORMAL,gtk.gdk.color_parse(self.COLOR_WRONG))
        except:
            print "REGEX COMPILATION ERROR !!!"
        